package com.cgnpc.scp.hse.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cgnpc.cud.core.domain.AjaxResult;
import com.cgnpc.cuddemo.utils.IDHelper;
import com.cgnpc.scp.common.bean.MyPageResult;
import com.cgnpc.scp.common.pojo.UserInfo;
import com.cgnpc.scp.common.utils.AjaxResultUtil;
import com.cgnpc.scp.common.utils.ListUtil;
import com.cgnpc.scp.common.utils.MyPageResultUtil;
import com.cgnpc.scp.common.utils.StringUtil;
import com.cgnpc.scp.hse.mybatis.entity.HseMeetingFile;
import com.cgnpc.scp.hse.mybatis.mapper.client.HseMeetingFileMapper;
import com.cgnpc.scp.hse.service.IHseMeetingFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

@Service
public class HseMeetingFileServiceImpl implements IHseMeetingFileService {
    private static final Logger LOGGER = LoggerFactory.getLogger(HseMeetingFileServiceImpl.class);

    @Autowired
    private HseMeetingFileMapper hseMeetingFileMapper;

    @Autowired
    private MessageSource messageSource;

    /**
     * 创建查询Example
     *
     * @param reqEntity reqEntity
     * @param <T>       T
     * @return Example
     */
    private <T extends HseMeetingFile> QueryWrapper<T> createQueryExample(T reqEntity) {
        // mybatis查询方式
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();

        // 设置排序字段
        queryWrapper.orderByAsc("order_index");

        // 设置查询条件

        // 会议ID
        queryWrapper.eq("meeting_info_id", reqEntity.getMeetingInfoId());

        return queryWrapper;
    }

    @Override
    public <T extends HseMeetingFile> MyPageResult<T> loadByPaging(T reqEntity) {
        // begin 分页查询
        // 第几页
        int pageNum = reqEntity.getPageNum();
        // 每页的数量
        int pageSize = reqEntity.getPageSize();

        // 创建Page对象
        IPage<HseMeetingFile> queryPage = new Page<>();
        queryPage.setCurrent(pageNum);
        queryPage.setSize(pageSize);

        // 创建queryExample
        QueryWrapper<HseMeetingFile> queryWrapper = createQueryExample(reqEntity);

        IPage<HseMeetingFile> pageResult = hseMeetingFileMapper.selectPage(queryPage, queryWrapper);

        // 创建分页结果集对象
        MyPageResult<HseMeetingFile> myPageResult = MyPageResultUtil.createMyPageResultPlus(pageResult);
        // end 分页查询

        return (MyPageResult<T>) myPageResult;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public <T extends HseMeetingFile> AjaxResult save(UserInfo loginUserInfo, Locale reqLocale, List<T> reqEntityList) {
        final String logInfo = "[HseMeetingFile_save_UUID_" + UUID.randomUUID().toString() + "]";

        try {
            if (ListUtil.getListSizeWith0(reqEntityList) <= 0) {
                LOGGER.warn("{}reqEntityList.size <= 0", logInfo);
                return AjaxResultUtil.createI18nErrorDefaultMessage(reqLocale, messageSource);
            }

            int saveRows = 0;

            for (T reqEntity : reqEntityList) {
                reqEntity.setId(IDHelper.uuidNew());
                saveRows += hseMeetingFileMapper.insert(reqEntity);
            }

            return AjaxResultUtil.createI18nSuccessDefaultMessage(reqLocale, messageSource);
        } catch (Exception e) {
            LOGGER.error("{}error;", logInfo, e);
            throw e;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public <T extends HseMeetingFile> AjaxResult updateWithMeetingInfoUpdate(UserInfo loginUserInfo, Locale reqLocale, String reqMeetingInfoId, List<T> reqEntityList) {
        final String logInfo = "[HseMeetingFile_updateWithMeetingInfoUpdate_UUID_" + UUID.randomUUID().toString() + "]";

        try {
            /**
             * 1.判断reqEntityList，如果为长度为0的List集合，则删除所有的附件。<br>
             * 2.Hse会议修改接口没有上传附件的功能，只是记录哪些附件还是有效的，所以不需要判断保存附件。<br>
             */

            if (StringUtil.isNullOrSpace(reqMeetingInfoId) || reqEntityList == null) {
                LOGGER.warn("{}reqEntityList.size <= 0", logInfo);
                return AjaxResultUtil.createI18nErrorDefaultMessage(reqLocale, messageSource);
            }

            if (ListUtil.getListSizeWith0(reqEntityList) <= 0) {
                UpdateWrapper<HseMeetingFile> delWrapper = new UpdateWrapper<>();

                delWrapper.eq("meeting_info_id", reqMeetingInfoId);

                int hseMeetingFileDelRows = hseMeetingFileMapper.delete(delWrapper);
                LOGGER.info("{}hseMeetingFileDelRows:{};", logInfo, hseMeetingFileDelRows);
                return AjaxResultUtil.createI18nSuccessDefaultMessage(reqLocale, messageSource);
            }

            List<String> reqEntityIdList = new ArrayList<>();

            for (T reqEntity : reqEntityList) {
                reqEntityIdList.add(reqEntity.getId());
            }

            UpdateWrapper<HseMeetingFile> delWrapper = new UpdateWrapper<>();

            delWrapper.eq("meeting_info_id", reqMeetingInfoId);
            delWrapper.notIn("id", reqEntityIdList);

            int hseMeetingFileDelRows = hseMeetingFileMapper.delete(delWrapper);
            LOGGER.info("{}hseMeetingFileDelRows:{};reqEntityIdList:{};"
                    , logInfo
                    , hseMeetingFileDelRows
                    , reqEntityIdList
            );

            return AjaxResultUtil.createI18nSuccessDefaultMessage(reqLocale, messageSource);
        } catch (Exception e) {
            LOGGER.error("{}error;", logInfo, e);
            throw e;
        }
    }

    @Override
    public <T extends HseMeetingFile> List<T> queryByMeetingInfoId(String reqMeetingInfoId) {
        if (StringUtil.isNullOrSpace(reqMeetingInfoId)) {
            return null;
        }

        QueryWrapper<HseMeetingFile> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("meeting_info_id", reqMeetingInfoId);

        return (List<T>) hseMeetingFileMapper.selectList(queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public <T extends HseMeetingFile> AjaxResult deleteById(List<String> reqMeetingInfoIdList) {
        final String logInfo = "[HseMeetingFile_deleteById_UUID_" + UUID.randomUUID() + "]";
        AjaxResult ajaxResult = null;

        try {
            if (ListUtil.getListSizeWith0(reqMeetingInfoIdList) <= 0) {
                return AjaxResultUtil.createErrorMessage("请求信息不正确", null);
            }

            LOGGER.info("{}reqMeetingInfoIdList:{};"
                    , logInfo
                    , reqMeetingInfoIdList
            );

            UpdateWrapper<HseMeetingFile> delWrapper = new UpdateWrapper<>();

            delWrapper.in("meeting_info_id", reqMeetingInfoIdList);

            int delRows = hseMeetingFileMapper.delete(delWrapper);

            ajaxResult = AjaxResultUtil.createSuccessMessage("删除成功", delRows);
        } catch (Exception e) {
            LOGGER.error("{}error;", logInfo, e);
            throw e;
        }

        return ajaxResult;
    }
}
